/*
* ============================================================================
* 功能描述 ：GPIO模拟I2C功能温湿度
* 作者       ：ggls
* 创建日期 ：2024.04.24
* ----------------------------------------------------------------------------
* 更新历史 ：
*	日期 　　- 修改者   : 更新内容描述
*
* ============================================================================
*/

#include "main.h"


//模拟IIC初始化
void I2CInit()
{
    SCL_out;
    SDA_out;
}


void I2C_delay()
{
   Delayus(20);
 
}

void I2CStart()
{
    SDA_out;
    SCL_H;
    SDA_H;
	_nop();_nop();_nop();_nop();
    SDA_L;
	_nop();_nop();_nop();_nop();
    SCL_L;
}

void I2CStop()
{
    SDA_out;
    SCL_L;
    SDA_L;
	_nop();_nop();_nop();_nop();
    SCL_H;
	_nop();_nop();_nop();_nop();
    SDA_H;
	_nop();_nop();_nop();_nop();
}

unsigned char I2CWrite(unsigned char I2Cdata)
{
     unsigned char mask;

     SDA_out;
     for (mask = 0x80; mask != 0; mask >>= 1)
     {
         if (mask & I2Cdata)
             SDA_H;
         else
             SDA_L;
		 _nop();_nop();_nop();_nop();
         SCL_H;
		 _nop();_nop();_nop();_nop();
         SCL_L;
     }
     SDA_H;
     SDA_in;
	 _nop();_nop();_nop();_nop();
     SCL_H;
	 _nop();_nop();_nop();_nop();
     if(RB5)
     {
         SCL_L;
         return 0;
     }
     else
     {
         SCL_L;
         return 1;
     }
}
unsigned char I2CAddress(unsigned char address)
{
    unsigned char ack = 0;

     I2CStart();
     ack = I2CWrite(address);
     I2CStop();

     return ack;
}
unsigned char I2CReadACK()
{
     unsigned char mask;
     unsigned char I2Cdata;

     SDA_H;
     SDA_in;

     for(mask = 0x80;mask != 0; mask >>= 1)
     {
		 _nop();_nop();_nop();_nop();
         SCL_H;
          if(RB5 == 0)
              I2Cdata &= ~mask;
          else
              I2Cdata |= mask;
		  _nop();_nop();_nop();_nop();
          SCL_L;
     }
     SDA_out;
     SDA_L;
	 _nop();_nop();_nop();_nop();
     SCL_H;
	 _nop();_nop();_nop();_nop();
     SCL_L;

     return I2Cdata;
}
unsigned char I2CReadNAK()
{
     unsigned char mask;
     unsigned char I2Cdata;

     SDA_H;
     SDA_in;

     for(mask = 0x80;mask != 0; mask >>= 1)
     {
		 _nop();_nop();_nop();_nop();
          SCL_H;
          if(RB5 == 0)
              I2Cdata &= ~mask;
          else
              I2Cdata |= mask;
		  _nop();_nop();_nop();_nop();
          SCL_L;
     }
     SDA_out;
     SDA_H;
	 _nop();_nop();_nop();_nop();
     SCL_H;
	 _nop();_nop();_nop();_nop();
     SCL_L;

     return I2Cdata;
}
